<template>
  <div class="app-container">
    <div class="department-layout">
      <!-- 左侧部门分类树 -->
      <!-- <div class="department-sidebar">
        <div class="sidebar-header">部门分类</div>
        <div class="search-box">
          <el-input
            v-model="categoryKeyword"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="el-icon-search"
          >
          </el-input>
        </div>
        <div class="tree-container">
          <el-tree
            ref="tree"
            :data="categoryTree"
            :props="defaultProps"
            node-key="id"
            default-expand-all
            highlight-current
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node }" class="custom-tree-node">
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
        </div>
      </div> -->

      <!-- 右侧主内容区 -->
      <div class="department-main">
        <!-- 顶部搜索和操作按钮 -->
        <!-- <div class="main-header">
          <div class="search-bar">
            <el-input
              v-model="departmentListQuery.name"
              placeholder="请输入部门名称"
              clearable
              style="width: 250px"
            />
            <el-button
              type="primary"
              style="margin-left: 10px"
              @click="handleFilter"
            >查询</el-button>
          </div>
          <div class="button-group">
          </div>
        </div> -->

        <!-- 表格区域 - 修改为树形表格 -->
        <el-table
          v-loading="listLoading"
          :data="departmentTree"
          element-loading-text="加载中"
          border
          fit
          row-key="id"
          :tree-props="{ children: 'list', hasChildren: 'hasChildren' }"
          highlight-current-row
        >
          <el-table-column
            label="部门名称"
            prop="name"
            align="center"
            min-width="200"
          >
            <template slot-scope="scope">
              <span
                :style="
                  scope.row.type === 'Organization'
                    ? 'font-weight: bold; color: #409EFF;'
                    : ''
                "
              >
                {{ scope.row.name }}
              </span>
              <el-tag
                v-if="scope.row.type === 'Organization'"
                size="mini"
                type="primary"
                style="margin-left: 8px"
              >组织</el-tag>
              <el-tag
                v-else
                size="mini"
                type="info"
                style="margin-left: 8px"
              >部门</el-tag>
            </template>
          </el-table-column>

          <!-- <el-table-column
            label="部门编号"
            prop="coding"
            align="center"
            width="120"
          /> -->

          <!-- <el-table-column label="层级排序" align="center" min-width="200">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.hierarchicalSort" placement="top">
                <span>{{
                  formatHierarchicalPath(scope.row.hierarchicalSort)
                }}</span>
              </el-tooltip>
            </template>
          </el-table-column> -->

          <!-- <el-table-column
            label="备注"
            prop="remark"
            align="center"
            min-width="150"
          /> -->

          <!-- <el-table-column label="状态" align="center" width="100"> -->
          <!-- <template slot-scope="scope">
              <el-tag type="success">正常</el-tag>
            </template> -->

          <!-- </el-table-column> -->

          <!-- <el-table-column label="操作" width="250" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="handleEdit(scope.row)"
                disabled
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="mini"
                @click="handleDelete(scope.row)"
                disabled
              >
                删除
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>

        <!-- 保留分页区域但只在非树形模式时使用 -->
        <el-row
          v-if="!isTreeMode"
          :gutter="10"
          style="margin-top: 20px"
          type="flex"
          justify="end"
        >
          <el-pagination
            background
            :current-page.sync="departmentListQuery.page"
            :page-sizes="[10, 20, 30, 40, 50]"
            :page-size="departmentListQuery.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
    </div>

    <!-- 新增/编辑部门对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="500px"
    >
      <el-form
        ref="departmentForm"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="部门类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择部门类型">
            <el-option label="组织机构" value="Organization" />
            <el-option label="部门" value="Department" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="addForm.parentMode" label="上级部门" prop="parent">
          <el-input
            v-model="addForm.parentName"
            placeholder="上级部门"
            disabled
          />
        </el-form-item>

        <el-form-item label="部门编号" prop="coding">
          <el-input
            v-model="addForm.coding"
            placeholder="请输入部门编号"
          />
        </el-form-item>

        <el-form-item label="部门名称" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入部门名称"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="addForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selDepartmentListApi,
  addDepartmentApi,
  updateDepartmentApi,
  deleteDepartmentApi
} from '@/api/system'

export default {
  name: 'DepartmentManagement',
  data() {
    return {
      listLoading: false,
      isTreeMode: true, // 默认使用树形模式
      departmentTree: [], // 树形结构的部门数据
      total: 0,
      // 部门列表查询
      departmentListQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      departmentList: [], // 扁平结构的部门列表
      // 表单数据
      addForm: {
        id: '',
        coding: '', // 编号
        name: '', // 名称
        remark: '', // 备注
        type: 'Department', // 默认为普通部门
        parent: '', // 上级部门ID
        parentName: '', // 上级部门名称
        parentMode: false // 是否为子部门模式
      },
      // 表单验证规则
      rules: {
        coding: [
          { required: true, message: '请输入部门编号', trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
        type: [
          { required: true, message: '请选择部门类型', trigger: 'change' }
        ]
      },
      dialogFormVisible: false
    }
  },
  computed: {
    dialogTitle() {
      if (this.addForm.id) {
        return this.addForm.parentMode ? '添加子部门' : '编辑部门'
      }
      return '新增部门'
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    // 获取部门列表
    async getDepartmentList() {
      this.listLoading = true
      try {
        // 调用API获取数据
        const res = await selDepartmentListApi(this.departmentListQuery)

        if (this.isTreeMode) {
          // 转换为树形结构
          this.departmentTree = this.buildDepartmentTree(res.data || [])
        } else {
          // 保持扁平结构
          this.departmentList = res.records || []
          this.total = res.total || 0
        }
      } catch (error) {
        console.error('获取部门列表失败:', error)
        this.departmentTree = []
        this.departmentList = []
        this.total = 0
        this.$message.error('获取部门列表失败')
      } finally {
        this.listLoading = false
      }
    },

    // 将扁平数据转换为树形结构
    buildDepartmentTree(flatData) {
      // 如果数据中已经有树形结构，直接返回
      if (flatData.length > 0 && flatData[0].list) {
        return flatData
      }

      // 否则构建树形结构
      const rootNodes = flatData.filter((item) => !item.parent)
      const buildTree = (nodes) => {
        return nodes.map((node) => {
          const children = flatData.filter((item) => item.parent === node.id)
          return {
            ...node,
            list: children.length > 0 ? buildTree(children) : [],
            hasChildren: children.length > 0
          }
        })
      }

      return buildTree(rootNodes)
    },

    // 格式化层级路径显示
    formatHierarchicalPath(path) {
      if (!path) return '-'
      return path.replace(/,/g, ' > ')
    },

    // 分页处理
    handleSizeChange(val) {
      this.departmentListQuery.pageSize = val
      this.getDepartmentList()
    },

    handleCurrentChange(val) {
      this.departmentListQuery.page = val
      this.getDepartmentList()
    },

    // 搜索处理
    handleFilter() {
      this.departmentListQuery.page = 1
      this.getDepartmentList()
    },

    // 新增部门处理
    handleAdd() {
      this.dialogFormVisible = true
      this.resetForm()
    },

    // 添加子部门
    handleAddChild(row) {
      this.dialogFormVisible = true
      this.resetForm()
      this.addForm.parentMode = true
      this.addForm.parent = row.id
      this.addForm.parentName = row.name

      // 如果是添加到组织下，默认类型为部门
      if (row.type === 'Organization') {
        this.addForm.type = 'Department'
      }
    },

    // 编辑部门处理
    handleEdit(row) {
      this.dialogFormVisible = true
      this.addForm = {
        id: row.id,
        coding: row.coding || '',
        name: row.name,
        remark: row.remark || '',
        type: row.type || 'Department',
        parent: row.parent || '',
        parentMode: false
      }
    },

    // 重置表单
    resetForm() {
      this.addForm = {
        id: '',
        coding: '',
        name: '',
        remark: '',
        type: 'Department',
        parent: '',
        parentName: '',
        parentMode: false
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.departmentForm.validate(async(valid) => {
        if (valid) {
          try {
            const params = {
              coding: this.addForm.coding,
              name: this.addForm.name,
              remark: this.addForm.remark || '',
              type: this.addForm.type
            }

            // 如果是添加子部门，需要包含父部门ID
            if (this.addForm.parentMode || this.addForm.parent) {
              params.parent = this.addForm.parent
            }

            if (!this.addForm.id) {
              // 新增部门 - 不包含id字段
              const res = await addDepartmentApi(params)
              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '新增成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            } else {
              // 编辑部门 - 需要包含id字段
              const res = await updateDepartmentApi({
                ...params,
                id: this.addForm.id
              })
              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '编辑成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            }

            this.dialogFormVisible = false
            this.getDepartmentList() // 刷新列表数据
          } catch (error) {
            console.error('操作失败:', error)
            this.$message({
              type: 'error',
              message: '操作失败: ' + (error.message || '未知错误')
            })
          }
        }
      })
    },

    // 删除部门处理
    handleDelete(row) {
      // 检查是否有子部门，如果有则不允许删除
      if (row.list && row.list.length > 0) {
        return this.$message({
          type: 'warning',
          message: '该部门下存在子部门，请先删除子部门'
        })
      }

      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            const res = await deleteDepartmentApi(row.id)
            if (res.code === 1) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getDepartmentList() // 刷新列表数据
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message({
              type: 'error',
              message: '删除失败: ' + (error.message || '未知错误')
            })
          }
        })
        .catch(() => {
          // 用户取消删除操作
        })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.department-layout {
  display: flex;
  min-height: calc(100vh - 120px);
  border: 1px solid #ebeef5;
}

.department-sidebar {
  width: 300px;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 15px;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
}

.search-box {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.tree-container {
  flex: 1;
  overflow: auto;
  padding: 10px;
}

.department-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 15px;
}

.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.search-bar {
  display: flex;
  align-items: center;
}

.button-group {
  text-align: right;
}

.dialog-footer {
  text-align: center;
}

/* 树形表格样式 */
.el-table__expand-icon {
  color: #409eff;
}

.department-tree-node {
  display: flex;
  align-items: center;
}

.org-name {
  font-weight: bold;
  color: #409eff;
}
</style>
